package com.loyal.camerax.ui.settings.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.loyal.camerax.databinding.AdapterGalleryBinding
import com.loyal.camerax.databinding.FragmentGalleryBinding
import com.loyal.camerax.ui.CameraViewModel
import com.loyal.camerax.utils.MediaStoreFile

open class GalleryFragment : Fragment() {

    private var _binding: FragmentGalleryBinding? = null
    private val binding get() = _binding!!
    private var galleryAdapter: MediaPagerAdapter? = null
    private val args: GalleryFragmentArgs by navArgs()
    private val viewModel: CameraViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        _binding = FragmentGalleryBinding.inflate(inflater, container, false)
        viewModel.updateStatus(223)
        return binding.root
    }

    open fun updateGallery(mediaList: MutableList<MediaStoreFile>) {
        if (mediaList.isEmpty()) {
            backToLast()
            return
        }
        galleryAdapter?.setMediaListAndNotify(mediaList)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        galleryAdapter = MediaPagerAdapter()
        binding.recyclerView.adapter = galleryAdapter
        galleryAdapter?.setCallback(object : AdapterCallback {
            override fun callback(what: Int, obj: Any?) {
                Log.e(TAG, "callback: $what,$tag")
                val action = GalleryFragmentDirections.actionToPhoto()
                action.setPosition(what)
                findNavController().navigate(action)
            }
        })

        // Handle back button press
        binding.backButton.setOnClickListener {
            backToLast()
        }
    }

    private fun backToLast() {
        val navigateUp = findNavController().navigateUp()
        Log.e(TAG, "navigateUp: $navigateUp")
        if (!navigateUp)
            activity?.finish()
    }

    private inner class MediaPagerAdapter : RecyclerView.Adapter<MediaPagerAdapter.ViewHolder>() {
        private var callback: AdapterCallback? = null
        private var mediaList = mutableListOf<MediaStoreFile>()

        private inner class ViewHolder(val binding: AdapterGalleryBinding) :
            RecyclerView.ViewHolder(binding.root)

        fun setCallback(callback: AdapterCallback?) {
            this.callback = callback
        }

        override fun getItemCount(): Int {
            return mediaList.size
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val binding =
                AdapterGalleryBinding.inflate(LayoutInflater.from(parent.context), parent, false)
            val spanCount: Int
            if (parent is RecyclerView) {
                val manager = parent.layoutManager
                if (manager is GridLayoutManager) {
                    spanCount = manager.spanCount
                    val itemSize = manager.width / spanCount
                    val rootLayoutParams = binding.root.layoutParams
                    rootLayoutParams.height = itemSize
                    binding.root.layoutParams = rootLayoutParams
                }
            }

            return ViewHolder(binding)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val resource = mediaList[position].file
            holder.binding.root.let {
                Glide.with(it).load(resource).into(it)
                it.setOnClickListener {
                    callback?.callback(position, null)
                }
            }
        }

        override fun getItemId(position: Int): Long {
            return mediaList[position].id
        }

        fun setMediaListAndNotify(newList: MutableList<MediaStoreFile>) {
            val oldSize = mediaList.size
            mediaList.clear()
            notifyItemRangeRemoved(0, oldSize)
            mediaList.addAll(newList)
            notifyItemRangeChanged(0, newList.size)

            val count = itemCount
            notifyItemRangeChanged(0, count)
        }
    }

    override fun onResume() {
        super.onResume()
        Log.e(TAG, "onResume: " + galleryAdapter?.itemCount)
    }

    override fun onDestroyView() {
        _binding = null
        //viewModel.status.removeObservers(viewLifecycleOwner)
        super.onDestroyView()
    }

    interface AdapterCallback {
        fun callback(what: Int, obj: Any?)
    }

    companion object {
        private const val TAG = "GalleryFragment"
    }
}